package com.ruoyi.system.service.impl.fxImpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.GeneralStatus;
import com.ruoyi.common.enums.SupplierGoodEnum;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.CodeGeneratorUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.fx.FxStore;
import com.ruoyi.system.domain.fx.FxSupplierGood;
import com.ruoyi.system.domain.fx.FxToJoin;
import com.ruoyi.system.domain.fx.FxUser;
import com.ruoyi.system.mapper.fx.FxStoreMapper;
import com.ruoyi.system.mapper.fx.FxSupplierGoodMapper;
import com.ruoyi.system.mapper.fx.FxUserMapper;
import com.ruoyi.system.service.fx.IFxSupplierGoodService;
import com.ruoyi.system.service.fx.IFxToJoinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;


/**
 * 供应商商品Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@Service
public class FxSupplierGoodServiceImpl extends ServiceImpl<FxSupplierGoodMapper,FxSupplierGood> implements IFxSupplierGoodService {
    @Autowired
    private FxSupplierGoodMapper fxSupplierGoodMapper;
    @Autowired
    private FxStoreMapper storeMapper;
    @Autowired
    private IFxToJoinService fxToJoinService;
    @Autowired
    private FxUserMapper fxUserMapper;
    /**
     * 查询供应商商品
     *
     * @param id 供应商商品主键
     * @return 供应商商品
     */
    @Override
    public FxSupplierGood selectFxSupplierGoodById(Long id) {
        FxSupplierGood supplierGood = Optional.ofNullable(fxSupplierGoodMapper.selectFxSupplierGoodById(id))
                .map(good -> {
                    if (StringUtils.isNotEmpty(good.getSpecifications())) {
                        List<String> list = Arrays.asList(good.getSpecifications().split(";"));
                        good.setSpecificationsList(list);
                    }
                    return good;
                })
                .orElse(null);
        return supplierGood;
    }

    @Override
    public List<FxSupplierGood> listByClassify(FxSupplierGood fxSupplierGood) {
        return fxSupplierGoodMapper.selectFxSupplierGoodList(fxSupplierGood);
    }
    /**
     * 查询供应商商品列表
     *
     * @param fxSupplierGood 供应商商品
     * @return 供应商商品
     */
    @Override
    public List<FxSupplierGood> selectFxSupplierGoodList(FxSupplierGood fxSupplierGood) {
        // 设置删除 标志
        fxSupplierGood.setDelFlag(Convert.toInt(GeneralStatus.存在.getCode()));
        // 获取当前登录人id
        Long userId = SecurityUtils.getUserId();
        // 判断是否是超级管理员
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles()
                .stream().map(SysRole::getRoleId).collect(Collectors.toList());
        fxSupplierGood.setSource(SupplierGoodEnum.SUPPLIER_SOURCE.getCode());
        if (roles.contains(1L) || roles.contains(6L)) {
            startPage();
            return fxSupplierGoodMapper.selectFxSupplierGoodList(fxSupplierGood);
        }
        FxUser fxUser = fxUserMapper.selectFxUserByUserId(userId);
        if (StringUtils.isNull(fxUser)) {
            throw new GlobalException("当前登录人信息有误");
        }
//        List<FxSupplierGood> goodList = fxSupplierGoodMapper.selectFxSupplierGoodList(fxSupplierGood);
        List<FxSupplierGood> goodList = new ArrayList<>();
        // 为空 是门店 用区域查询
        if (roles.contains(4L)) {
            FxStore fxStore = storeMapper.selectFxStoreByUserId(userId);
            if (ObjectUtils.isEmpty(fxStore))
                return new ArrayList<>();
            fxSupplierGood.setRegion(String.valueOf(fxStore.getRegion()));
            fxSupplierGood.setStatus(2L); // 2审核通过
            fxSupplierGood.setIsInitiate(0); // 0上架
            fxSupplierGood.setUserId(null);
        }
        if (roles.contains(3L)) {
            fxSupplierGood.setSupplierId(fxUser.getParentAccountId());
        }
        startPage();
        goodList = Optional.of(fxSupplierGoodMapper.selectFxSupplierGoodList(fxSupplierGood)).orElse(Collections.emptyList()); // 查询区域 供应商商品
        return goodList;
    }

    @Override
    public List<FxSupplierGood> selectFxSupplierSonGoodList(FxSupplierGood fxSupplierGood) {
        return fxSupplierGoodMapper.selectFxSupplierSonGoodList(fxSupplierGood);
    }

    @Override
    public List<FxSupplierGood> selectFxStoreSupplierGoodList(FxSupplierGood fxSupplierGood) {
        return fxSupplierGoodMapper.selectFxStoreSupplierGoodList(fxSupplierGood);
    }

    /**
     * 新增供应商商品
     *
     * @param fxSupplierGood 供应商商品
     * @return 结果
     */
    @Override
    public int insertFxSupplierGood(FxSupplierGood fxSupplierGood) {
        if (StringUtils.isNotNull(this.exist(fxSupplierGood.getGoodName()))) {
            throw new GlobalException("“"+ fxSupplierGood.getGoodName() + "”，名称已存在");
        }
        fxSupplierGood.setCreateTime(DateUtils.getNowDate());
        String goodId = System.currentTimeMillis() + "" + ThreadLocalRandom.current().nextInt(100, 1000);
        fxSupplierGood.setId(Convert.toLong(goodId));
        fxSupplierGood.setSource(1); // 1供应商
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<Long> role = sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());

        //如果是供应商
        if(role.contains(3L)){
            FxToJoin fxToJoin=new FxToJoin();
            fxToJoin.setPhone(sysUser.getPhonenumber());
            List<FxToJoin> list= fxToJoinService.selectFxToJoinList(fxToJoin);
            fxSupplierGood.setSupplierId(list.get(0).getId());
            fxSupplierGood.setCreaterName(list.get(0).getStoreName());
        }else{
            fxSupplierGood.setCreaterName(sysUser.getNickName());
        }
        fxSupplierGood.setUserId(sysUser.getUserId());
//        fxSupplierGood.setSupplierId();
        fxSupplierGood.setCreaterName(sysUser.getNickName());
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        // 将日期格式化为指定格式的字符串
        String formattedDate = currentDate.format(formatter);
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath() + "/barCode/" + formattedDate;
        String imgUrl = CodeGeneratorUtil.generateBarCode(goodId, 400, 100, filePath);
        fxSupplierGood.setQrCodeUrl("/profile/upload/barCode/" + formattedDate + imgUrl); // 二维码生成
        fxSupplierGood.setGrandCounts(fxSupplierGood.getCounts());
        return fxSupplierGoodMapper.insertFxSupplierGood(fxSupplierGood);
    }

    /**
     * 修改供应商商品
     *
     * @param fxSupplierGood 供应商商品
     * @return 结果
     */
    @Override
    public int updateFxSupplierGood(FxSupplierGood fxSupplierGood) {
        boolean hasReviewPermission = SecurityUtils.hasRole("1") || SecurityUtils.hasRole("6");
        if (!hasReviewPermission){
            fxSupplierGood.setStatus(null);
        }
        Long status = fxSupplierGood.getStatus();
        if (status != null && (status == 2 || status == 3)) {
            if (!hasReviewPermission){
                throw new GlobalException("无审核权限，请联系管理员");
            }
        }


        FxSupplierGood supplierGood = fxSupplierGoodMapper.selectFxSupplierGoodById(fxSupplierGood.getId());
        if (StringUtils.isNull(supplierGood)) {
            throw new GlobalException("此商品信息错误");
        }
        List<Long> role = SecurityUtils.getLoginUser().getUser().getRoles()
                .stream().map(SysRole::getRoleId).collect(Collectors.toList());
        if (!role.contains(1L) && !role.contains(6L)) {
            FxSupplierGood good = this.exist(fxSupplierGood.getGoodName());
            if (StringUtils.isNotNull(good) && !Objects.equals(good.getId(), fxSupplierGood.getId())) {
                throw new GlobalException( "“"+ fxSupplierGood.getGoodName() + "”，名称已存在" );
            }
        }
        Long isInitiate = Convert.toLong(fxSupplierGood.getIsInitiate());
        if (Objects.equals(isInitiate, GeneralStatus.是.getCode()) && (supplierGood.getStatus() == 3)) {
            throw new GlobalException("商品审核未通过,无法上架");
        }
        if (supplierGood.getStatus() == 3) {
            fxSupplierGood.setStatus(1L); // 重新提交
        }
        return fxSupplierGoodMapper.updateFxSupplierGood(fxSupplierGood);
    }

    /**
     * 补货
     * @param fxSupplierGood 参数
     * @return
     */
    @Override
    public int updateFxSupplierCounts(FxSupplierGood fxSupplierGood) {
        FxSupplierGood supplierGood = fxSupplierGoodMapper.selectFxSupplierGoodById(fxSupplierGood.getId());
        if (StringUtils.isNull(supplierGood)) {
            throw new GlobalException("此商品信息错误");
        }
        Long newCounts = supplierGood.getCounts() + fxSupplierGood.getCounts();
        Long newGrandCounts = supplierGood.getGrandCounts() + fxSupplierGood.getCounts();
        fxSupplierGood.setCounts(newCounts);
        fxSupplierGood.setGrandCounts(newGrandCounts);
        return fxSupplierGoodMapper.updateFxSupplierGood(fxSupplierGood);
    }

    /**
     * 批量修改 删除标志
     * @param ids
     * @return
     */
    @Override
    public int updateDelFlag(Long[] ids) {
        return fxSupplierGoodMapper.updateStatusByIds(ids,1,1);
    }

    /**
     * 批量删除供应商商品
     *
     * @param ids 需要删除的供应商商品主键
     * @return 结果
     */
    @Override
    public int deleteFxSupplierGoodByIds(Long[] ids) {
        return fxSupplierGoodMapper.deleteFxSupplierGoodByIds(ids);
    }

    /**
     * 删除供应商商品信息
     *
     * @param id 供应商商品主键
     * @return 结果
     */
    @Override
    public int deleteFxSupplierGoodById(Long id) {
        return fxSupplierGoodMapper.deleteFxSupplierGoodById(id);
    }

    /**
     * 是否存在
     * @param goodName 商品名称
     * @return
     */
    public FxSupplierGood exist(String goodName) {
        Long userId = SecurityUtils.getUserId();
        FxUser fxUser = fxUserMapper.selectFxUserByUserId(userId);
        if (StringUtils.isNull(fxUser))
            throw new GlobalException("用户信息错误！");
        Long supplierId = fxUser.getParentAccountId();
        return fxSupplierGoodMapper.selectSupplierByGoodName(goodName, supplierId);
    }
}
